<?php 
session_start();
require_once ("class/m_cancelbill.php");
require_once ("class/m_stock.php");
$m_stock=new M_stock();
$m = new M_cancelbill();

if (isset($_POST['m'])  &&  $_POST['m']!=""){
	if ($_POST['m']== 'search'){
		$page=$_POST['page'];
		$page=isset($page)?$page:1;
		//$branch=$_SESSION['bid']; // Show only branch
		
		if ($_SESSION['branchtype'] =="1")
			$branch=$_POST['barnchid'];
		else 
			$branch=$_SESSION['bid'];
				
		$billNo= $_POST['id'];
		$type= $_POST['type'];
		
		if ( $billNo!='' ){
			  $billNo = number_format(substr($billNo, -5),0);
		}	 
		 
		$result=$m->getData( $branch,$billNo,$_POST['datefrom'],$_POST['dateto'],$_POST['name'],$page,$type);
	 	//echo $result;
		$rows=$m->getRowCount();
		
		$i=1 + (($page-1) * $m->getListPage());
		
		$html="";
		if ($rows > 0){
			while($row = $result->FetchRow()){
				If($i%2 <> 0){
					$html .= "<tr class=row1>";
				} else{
					$html .= "<tr>";
				}
				$html .= genTable($row);
				$html .= "</tr>";
				$i++;
			}
		}else{
			$html="<tr>"
				."<td colspan='12' align='center' ><img src='./images/info.gif'/><b/></td>"
				."</tr>";
		}
		//Return result , rows , page
		$ar_result=array('data'=>$html,
						'rows'=>$rows,
						'totalpage'=>$m->getTotalPage());
		 echo json_encode( $ar_result );
		
	}else if ($_POST['m']== 'detail'){
		$id=$_POST['id'];
		$result=$m->getDataDetail($id);
		$rows=$m->getRowCount();
		$ar=$m->getPaymentHistory($id);
		$html="";
		$i=1;
		
		$head=$m->getHeaderData(0,$id);
		if ($rows > 0){
			while($row = $result->FetchRow()){
				$html .= getTableDetail($row,$i);
				$i++;
			}
		}
		
		$irow=count($ar);
		if ($irow>1){
			$paytype .=$ar[0]['PayType'] ." / ".$ar[1]['PayType'] ;
			//$paytype .=$ar[0]['PayType']."(".number_format($ar[0]['PaymentAmount'],2,'.',',').") / ".$ar[1]['PayType']. "(".number_format($ar[1]['PaymentAmount'],2,'.',',').")";
		}else{
			$paytype .=$ar[0]['PayType'];
			//$paytype .=$ar[0]['PayType']."(".number_format($ar[0]['PaymentAmount'],2,'.',',').")";
		}
		
		$headerResult= $head->FetchRow();
		$headerResult['Bill']=$headerResult["BranchCode"].$headerResult["BillNo"]. str_repeat('0' , 5-strlen($headerResult["ID"])). $headerResult["ID"];
		$arReturn=array('rows'=>$rows,
						'header'=>json_encode( $headerResult ),
						'paytype'=>$paytype,
						'data'=> $html);
		echo json_encode($arReturn);
		
	}else if ($_POST['m']=='cancel_detail'){ 
		$id=$_POST['id'];
		$isAll=$_POST['IsAll'];
		$arVal=$_POST['var'];
		$listid=substr($arVal,0,-1);
		
		if ($isAll=="1"){
			$m->cancelBill_Main($id,$_SESSION['username']);	
			$m->cancelBill_detail_all($id);
		}else{
			$m->cancelBill_detail($listid);
			$a=$m->updateBill($id);
		}
		echo $a;
	
	}else if ($_POST['m']== 'cancel'){
		$id=$_POST['id'];
		//Cancel Bill
		$user=$_SESSION['username'];
		
		if ( $m->checkAlreadyUsed($id) ){ 
			$ar=array('result'=>0,'msg'=>'Cannot cancel this bill because some course was used ');
			echo json_encode( $ar );
		}else {
			$m->cancelBill_Main($id,$user); 
			
			//Cancel stock
			$result=$m->getDataDetail($id);
			while($row = $result->FetchRow()){
				//Product
				 if ($row['PTypeId']==1){
					//Update stock
					$m_stock->UpdateReturnStockBranch($row['Pid'] , $_SESSION['bid'] ,$row["Amount"] , $user, 1);
					
				}else if ($row['PTypeId']==2 || $row['PTypeId']==3){
					$m_stock->Stock_Set_Treatment_Update($row['Pid'] , $_SESSION['bid'] ,$row["Amount"] , $user, 1);
				}
				 
			}
			$ar=array('result'=>1,'msg'=>'Completed');
			echo json_encode( $ar );
		 }
		

	}
}
	function getTableDetail($row,$i){
		If($i%2 <> 0){
			$html .= "<tr class=row1>";
		} else{
			$html .= "<tr>";
		}
		$html .= "<td align='right'>".$i."</td>";
		$html .= "<td style='display:none'>".$row["id"]."</td>";
		$html .= "<td align='left'>".$row["ProductName"]."</td>";
		$html .= "<td align='center'>".$row["CatName"]."</td>";
		$html .= "<td align='center'>".$row["ProductType"]."</td>";
		$html .= "<td align='right'>".$row["Amount"]." - ". $row["Unit"]."</td>";
		$html .= "<td align='right'>".number_format($row["Total"],2,'.',',')."</td>";
		$html .= "<td align='right' style='color:red'>".number_format($row["Discount"],2,'.',',')."</td>";
		$html .= "<td align='right' style='font-weight:bold;color:blue'>".number_format($row["TotalAmt"],2,'.',',')."</td>";
		//$html .= "<td align='center'><input type='checkbox' value='".$row["id"]."' name='chkCancel'/></td>";
		$html .= "</tr>";
		return $html;
	}
	function genTable($row){
		global $posScreen;
		
		$s="";
		$s.="<td align='center'>".$row["BranchCode"].$row["BillNo"].str_repeat('0' , 5-strlen($row["ID"])). $row["ID"] ."</td>";
		$s.="<td align='center' style='display:none'>".$row["ID"]."</td>";
		$s.="<td align='center' >".$row["BranchName"]."</td>";
		if ($row['CustID']==1)
			$s.="<td align='left'>".$row["Name"]."</td>" ;
		else 
			$s.="<td align='left' style='color:red;font-weight:bold;'>".$row["Name"]."</td>" ;
			
		$s.="<td align='center'>".$row["SaleDate1"]." by <b>".$row["SaleBy"]."</b></td>" .
		"<td align='right' >". number_format( $row["Amount"],2,'.',',')."</td>" .
		"<td align='right' style='color:red;'>".number_format($row["Discount"],2,'.',',')."</td>" .
		"<td align='right' style='color:blue;'>".number_format($row["Total"],2,'.',',')."</td>" .
		"<td align='right'>".number_format($row["PaymentAmount"],2,'.',',')."</td>" .
		"<td align='center'>".
		"<img src='./images/print2.png' class='btnPrint' style='cursor:pointer' title='Re-Print' border='0'/>".
		"</td>".
		"<td align='center'>".
		"<img src='./images/view.png' class='btnView' style='cursor:pointer' title='View Detail ' border='0'/>".
		"</td>".
		"<td align='center'>";
		if ($row['IsCancel']==0){
			if ($_SESSION["permission"][$posScreen]["Add"]=="1") { 
				$s.="<img src='./images/cancelbill24.png' class='btnCancel' style='cursor:pointer' title='Cancel Bill' border='0'/>";
			}else {
				$s.=" ";
			}
		}
		$s.="</td>";
	return $s;
}
?>